# encoding: utf-8

module Capevaluation
  module Service
    class Example < CaiQiu::Core::ServiceBase
      class << self
        # 获取数据库连接
        def get_conn
          unless defined? @conn
            @conn = CaiQiu::Core::ServiceConn.DB_EXAMPLE
          end
          @conn
        end

        def add_example(value, status)
          example          = Capevaluation::Dao::Example.new
          example[:value]  = value
          example[:status] = status
          example.save
        end

        def get_example_by_value(value)
          example_list = []
          rows         = Capevaluation::Dao::Example.select(:id, :value, :status)
                             .where(:value => value)
          rows.each do |row|
            example_list.push row.to_hash
          end
          example_list
        end

        def get_example_by_id(id)
          example_list = []
          rows         = Capevaluation::Dao::Example.select(:id, :value, :status)
                             .where(:id => id)
          rows.each do |row|
            example_list.push row.to_hash
          end
          example_list
        end

        def list_examples
          example_list = []
          rows         = Capevaluation::Dao::Example.select(:id, :value, :status)
          rows.each do |row|
            example_list.push row.to_hash
          end
          example_list
        end

        def mod_example(example_hash)
          example_model = Capevaluation::Dao::Example.select(:id, :value, :status)
                              .where(:id => example_hash[:id]).first
          example_hash.each do |k, v|
            if example_model.columns.include? k
              if v != example_model[v]
                example_model[k] = v
              end
            end
          end
          example_model.save_changes
        end

        def mod_examples(example_list)
          example_list.each do |example|
            mod_example(example)
          end
        end

        def mod_value_by_status(example_hash)
          # 开启事务
          example_model = Capevaluation::Dao::Example.select(:id, :value, :status)
                              .where(:id => example_hash[:id]).first
          example_model.lock!
          if example_model[:status] == 0
            example_model[:value] = 'lock'
            example_model.save_changes
          end
        end

      end
    end
  end
end

